package com.example.demo1.dao;

import com.example.demo1.model.Organization;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface OrganizationMapper {

    @Insert("INSERT INTO organization(name, parent_id, path, level) " +
            "VALUES(#{name}, #{parentId}, #{path}, #{level})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Organization organization);

    @Update("UPDATE organization SET name=#{name} WHERE id=#{id}")
    int updateBasicInfo(Organization organization);

    @Update("UPDATE organization SET parent_id=#{parentId}, path=#{path}, level=#{level} WHERE id=#{id}")
    int updatePathInfo(Organization organization);

    @Delete("DELETE FROM organization WHERE id=#{id}")
    int delete(Integer id);

    @Select("SELECT * FROM organization WHERE id=#{id} FOR UPDATE")
    Organization findByIdForUpdate(Integer id);

    @Select("SELECT * FROM organization WHERE id=#{id}")
    Organization findById(Integer id);

    @Select("SELECT * FROM organization WHERE path LIKE CONCAT(#{path}, '%') AND id != #{id}")
    List<Organization> findDescendants(@Param("id") Integer id, @Param("path") String path);

    @Select("SELECT * FROM organization WHERE #{path} LIKE CONCAT(path, '%') AND id != #{id}")
    List<Organization> findAncestors(@Param("id") Integer id, @Param("path") String path);

    @Select("SELECT * FROM organization WHERE parent_id=#{parentId}")
    List<Organization> findByParentId(Integer parentId);

    @Select("SELECT * FROM organization ORDER BY path")
    List<Organization> findAll();

    @Update("UPDATE organization SET path=REPLACE(path, #{oldPath}, #{newPath}), " +
            "level=level + #{levelDiff} " +
            "WHERE path LIKE CONCAT(#{oldPath}, '%')")
    int updateDescendantsPaths(@Param("oldPath") String oldPath,
                               @Param("newPath") String newPath,
                               @Param("levelDiff") int levelDiff);

//    @Delete({
//            "<script>",
//            "DELETE FROM organization WHERE id IN",
//            "<foreach item='id' collection='ids' open='(' separator=',' close=')'>",
//            "#{id}",
//            "</foreach>",
//            "</script>"
//    })
//    int batchDeleteOrganizations(@Param("ids") List<Integer> ids);

//    @Select("SELECT * FROM organization WHERE path LIKE CONCAT(#{path}, '%') AND id != #{id}")
//    List<Organization> findDescendants(@Param("id") Integer id, @Param("path") String path);
}
